﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.IO;
using Kgb.Model.Models;
using Kgb.Web2.Util;
using System.Net.Http;
using System.Web.Http.Routing;

namespace Kgb.Web2.Repository
{
    public class RoomRepository
    {
        private string restService = ConfigurationManager.AppSettings["restService"];
        private RequestMethod requestMethod = new RequestMethod();
        ISerialization _serializer;

        public RoomRepository(ISerialization serializer)
        {
            _serializer = serializer;
        }

        public Room Get(int id)
        {
            var responseStream = requestMethod
                                .GetResponseStream(requestMethod
                                                   .getRequest("GET"
                                                              , "application/json"
                                                              , string.Format("{0}/rooms/{1}", restService, id)
                                                              )
                                                   .GetResponse()
                                                  );

            var room = _serializer.DeSerialize(responseStream) as Newtonsoft.Json.Linq.JObject;

            var ret = new Room
                      {
                          Id = (int)room["Id"]
                      ,
                          LobbyId = (int?)room["LobbyId"]
                      ,
                          Name = room["Name"].ToString()
                      ,
                          State = room["State"].ToString()
                      };

            return ret;
        }

        public List<Location> GetLocations(int roomId, int locationId)
        {
            var responseStream = requestMethod
                                .GetResponseStream(requestMethod
                                                   .getRequest("GET"
                                                              , "application/json"
                                                              , string.Format("{0}/rooms/locations/{1}?locationId={2}", restService, roomId.ToString(),locationId.ToString())
                                                              )
                                                   .GetResponse()
                                                  );

            var locations = _serializer.DeSerialize(responseStream) as Newtonsoft.Json.Linq.JArray;

            var ret = from l in locations
                      select new Location
                      {
                          Id = (int)l["Id"]
                      ,
                          RoomId = (int)l["Id"]
                      ,
                          Name = l["Name"].ToString()
                      ,
                          State = l["State"].ToString()
                      ,
                          LocationPlayer = !l["LocationPlayer"].HasValues ? null
                                                      : new Player {  Id = (int)l["LocationPlayer"]["Id"]
                                                      ,  Name = l["LocationPlayer"]["Name"].ToString()
                                                      ,  State = l["LocationPlayer"]["State"].ToString()
                                                      ,  LobbyId = (int)l["LocationPlayer"]["LobbyId"]
                                                      ,  RoomId = (int)l["LocationPlayer"]["RoomId"]
                                                      ,  SessionId = ""
                                                      }
                      };

            return ret.ToList();
        }

        public Player AccessRoom(Player player, Room room)
        {
            //precisa criar a classe action e melhora a chamada post do action
            var r = requestMethod.getRequest( "POST"
                                            , "application/json"
                                            , string.Format( "{0}/rooms/accessRoom/{1}?roomId={1}&playerId={2}&sessionId={3}"
                                                           , restService
                                                           , room.Id
                                                           , player.Id
                                                           , player.Session()
                                                           )
                                            , ""
                                            ).GetResponse();

            var location = r.Headers.Get("Location");

            Uri uri = new Uri(location);

            player.RoomId = int.Parse(uri.Segments.Last());
            return player;
        }
    }
}